package com.iflytek.aidemo;

import androidx.appcompat.app.AppCompatActivity;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.iflytek.aidemo.api.ApiService;
import com.iflytek.aidemo.api.ApiServiceImpl;
import com.iflytek.aidemo.model.ApiResponse;
import com.iflytek.aidemo.model.User;
import com.iflytek.aidemo.util.SessionManager;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RegisterActivity extends AppCompatActivity {

    private EditText etUsername, etPassword, etConfirmPassword;
    private Button btnRegister, btnModeTeacher, btnModeStudent;
    private TextView tvBackToLogin;
    private ProgressBar progressBar;
    private ImageView ivPasswordToggle, ivConfirmPasswordToggle;

    private ApiService apiService;
    private SessionManager sessionManager;
    private ExecutorService executorService;
    private Handler mainHandler;

    private String selectedMode = "老师"; // 默认选择老师
    private boolean isPasswordVisible = false;
    private boolean isConfirmPasswordVisible = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initViews();
        initData();
        setupListeners();

        // 初始化模式选择状态
        btnModeTeacher.setSelected(true);
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        etConfirmPassword = findViewById(R.id.et_confirm_password);
        btnRegister = findViewById(R.id.btn_register);
        tvBackToLogin = findViewById(R.id.tv_back_to_login);
        progressBar = findViewById(R.id.progress_bar);
        ivPasswordToggle = findViewById(R.id.iv_password_toggle);
        ivConfirmPasswordToggle = findViewById(R.id.iv_confirm_password_toggle);

        // 初始化模式选择按钮
        btnModeTeacher = findViewById(R.id.btn_mode_teacher);
        btnModeStudent = findViewById(R.id.btn_mode_student);
    }

    private void initData() {
        apiService = new ApiServiceImpl();
        sessionManager = new SessionManager(this);
        executorService = Executors.newSingleThreadExecutor();
        mainHandler = new Handler(Looper.getMainLooper());
    }

    private void setupListeners() {
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                performRegister();
            }
        });

        tvBackToLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 设置模式选择按钮点击事件
        btnModeTeacher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectMode(btnModeTeacher, "老师");
            }
        });

        btnModeStudent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectMode(btnModeStudent, "学生");
            }
        });

        // 添加密码显示/隐藏的点击事件
        ivPasswordToggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                togglePasswordVisibility();
            }
        });

        // 添加确认密码显示/隐藏的点击事件
        ivConfirmPasswordToggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleConfirmPasswordVisibility();
            }
        });
    }

    // 选择模式
    private void selectMode(Button selectedButton, String mode) {
        // 重置所有按钮状态
        btnModeTeacher.setSelected(false);
        btnModeStudent.setSelected(false);

        // 设置选中按钮状态
        selectedButton.setSelected(true);
        selectedMode = mode;

        // 执行选中动画
        performSelectAnimation(selectedButton);
    }

    // 执行选中动画
    private void performSelectAnimation(View view) {
        // 使用属性动画实现大小变化
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1.0f, 1.05f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1.0f, 1.05f);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(scaleX).with(scaleY);
        animatorSet.setDuration(200);
        animatorSet.start();
    }

    private void togglePasswordVisibility() {
        if (isPasswordVisible) {
            // 隐藏密码
            etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            ivPasswordToggle.setImageResource(R.drawable.ic_eye_closed);
            isPasswordVisible = false;
        } else {
            // 显示密码
            etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            ivPasswordToggle.setImageResource(R.drawable.ic_eye_open);
            isPasswordVisible = true;
        }
        
        // 将光标移动到文本末尾
        etPassword.setSelection(etPassword.getText().length());
    }

    private void toggleConfirmPasswordVisibility() {
        if (isConfirmPasswordVisible) {
            // 隐藏确认密码
            etConfirmPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            ivConfirmPasswordToggle.setImageResource(R.drawable.ic_eye_closed);
            isConfirmPasswordVisible = false;
        } else {
            // 显示确认密码
            etConfirmPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            ivConfirmPasswordToggle.setImageResource(R.drawable.ic_eye_open);
            isConfirmPasswordVisible = true;
        }
        
        // 将光标移动到文本末尾
        etConfirmPassword.setSelection(etConfirmPassword.getText().length());
    }

    private void performRegister() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();

        // 输入验证
        if (!validateInput(username, password, confirmPassword)) {
            return;
        }

        // 显示加载状态
        setLoadingState(true);

        // 在后台线程执行注册
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                int userType;
                if(selectedMode.equals("学生")){
                    userType=1;
                }else{
                    userType=2;
                }
                // 传递选中的模式到注册接口
                final ApiResponse<User> response = apiService.register(username, password, userType);

                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        setLoadingState(false);
                        handleRegisterResponse(response);
                    }
                });
            }
        });
    }

    private boolean validateInput(String username, String password, String confirmPassword) {
        // 用户名验证
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
            etUsername.requestFocus();
            return false;
        }
        if (username.length() < 3 || username.length() > 5) {
            Toast.makeText(this, "用户名长度应在3-5个字符之间", Toast.LENGTH_SHORT).show(); // 修正范围描述
            etUsername.requestFocus();
            return false;
        }

        // 密码验证
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            etPassword.requestFocus();
            return false;
        }
        if (password.length() < 6) {
            Toast.makeText(this, "密码长度不能少于6位", Toast.LENGTH_SHORT).show();
            etPassword.requestFocus();
            return false;
        }

        // 确认密码验证
        if (TextUtils.isEmpty(confirmPassword)) {
            Toast.makeText(this, "请确认密码", Toast.LENGTH_SHORT).show();
            etConfirmPassword.requestFocus();
            return false;
        }
        if (!password.equals(confirmPassword)) {
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            etConfirmPassword.requestFocus();
            return false;
        }

        return true;
    }

    private void handleRegisterResponse(ApiResponse<User> response) {
        if (response == null) {
            Toast.makeText(this, "网络连接失败，请检查网络设置", Toast.LENGTH_SHORT).show();
            return;
        }

        if (response.isSuccess()) {
            // 注册成功
            User user = response.getData();
            if (user != null) {
                // 保存用户会话
                sessionManager.saveUserSession(user);

                Toast.makeText(this, "注册成功！您选择的身份是：" + selectedMode, Toast.LENGTH_SHORT).show();

                // 跳转到主页面
                Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                finish();
            }
        } else {
            // 注册失败
            String errorMessage = response.getMessage();
            if (TextUtils.isEmpty(errorMessage)) {
                errorMessage = "注册失败，请稍后重试";
            }
            Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
        }
    }

    private void setLoadingState(boolean isLoading) {
        progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        btnRegister.setEnabled(!isLoading);
        btnRegister.setText(isLoading ? "注册中..." : "注册");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
        }
    }
}